package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //登陆操作
    @RequestMapping("/login")
    public String login(String email, String password) {
        User u = userService.findEmailAndPwd(email, password);
        if (u != null) {
            //登录成功
            return "main";
        } else {
            return "login";
        }
    }

    @RequestMapping("/list")
    public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize, Model model) {
        List<User> list = userService.findAll(pageNum, pageSize);

        //分页处理
        PageInfo<User> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo", pageInfo);
        return "list";
    }

    @RequestMapping(value = "/save", produces = "text/html;character=UTF-8")
    public String save(User user) {
        userService.save(user);
        return "redirect:/user/list";
    }

    @RequestMapping("/deleteById")
    public String delete(Integer id) {
        System.out.println(id + "-----------------");
        userService.deleteById(id);
        return "redirect:/user/list";
    }
}
